package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.model.Board;
import com.example.forum.services.IBoradService;
import javax.validation.constraints.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@Api(tags = "板块接口")
@RequestMapping("/board")
public class BoardController {

    @Autowired
    private IBoradService boradService;

    //首页中显示的板块个数 :9如果找不到 就设置默认为9
    @Value("${forum.index.board-num:9}")
    private Integer indexBoardNum;

    /**
     * 查询首页板块列表
     * @return 查询列表结果
     */
    @ApiOperation("获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList(){
        log.info("首页板块个数为: "+indexBoardNum);
        List<Board> boards=boradService.selectByNum(indexBoardNum);
        //判断是否为空  为空就返回一个空的
        if(boards==null){
            boards=new ArrayList<>();
        } else {
            // 为每个板块获取实时文章数量
            for (Board board : boards) {
                int actualCount = boradService.getActualArticleCount(board.getId());
                board.setArticleCount(actualCount);
            }
        }
        return AppResult.success(boards);
    }
    
    /**
     * 获取所有板块列表（公共接口）
     * @return 所有板块列表
     */
    @ApiOperation("获取所有板块列表")
    @GetMapping("/list")
    public AppResult<List<Board>> getAllBoards(){
        // 调用Service获取所有正常状态的板块
        List<Board> boards = boradService.getAllBoards();
        if(boards == null){
            boards = new ArrayList<>();
        } else {
            // 为每个板块获取实时文章数量
            for (Board board : boards) {
                int actualCount = boradService.getActualArticleCount(board.getId());
                board.setArticleCount(actualCount);
            }
        }
        return AppResult.success(boards);
    }

    @ApiOperation("获取板块信息")
    @PostMapping("/getById")
    public AppResult<Board> getById(@ApiParam("板块id") @RequestParam("id") @NotNull Long id){
        //调用Service
        Board board = boradService.selectById(id);
        //校验查询结果  表示板块不存咋 或者已删除
        if(board==null||board.getDeleteState()==1){
            //板块校验失败
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        
        // 获取实时文章数量
        int actualCount = boradService.getActualArticleCount(board.getId());
        board.setArticleCount(actualCount);
        
        //返回数据
        return AppResult.success(board);
    }

}
